package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.MyWindowFunction;
import com.atguigu.Util.ClickHouseUtil;
import com.atguigu.Util.DateFormatUtil;
import com.atguigu.Util.MyKafkaUtil;
import com.atguigu.bean.CartAddUuBean;
import com.atguigu.bean.UserLoginBean;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hjy
 * @create 2023/3/16 9:51
 */
//数据流:app/客户端->mysql->maxwell->kafka(topic_db  ods)->Dwd02_TradeCartAdd->kafka(dwd)->flickApp->clickhouse(dws)
//程 序:mock->mysql->maxwell->kafka(zk)->Dwd02_TradeCartAdd->kafka(zk)->Dws06_TradeCartAddUuWindow->clickhouse(dws)
public class Dws06_TradeCartAddUuWindow {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HAOOP_USER_NAME","atguigu");
        //todo 2 从kafka（dwd_cart_info）读取主题
        String topic ="dwd_cart_info";
        String groupId="dws06_trade_cart_add_uu_window";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));
        //todo 3 转化为jsonObj对象 加上时间戳
        SingleOutputStreamOperator<JSONObject> JSONObjWithWMDS = kafkaDS.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String value) throws Exception {
                return JSONObject.parseObject(value);
            }
        }).assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return DateFormatUtil.toTs(element.getString("create_time"), true);
                    }
                })));
        //todo 3.1 按照user_id分组
        KeyedStream<JSONObject, String> keyedStream = JSONObjWithWMDS.keyBy(value -> value.getString("user_id"));
        //todo 4 转为JAVABean对象
        SingleOutputStreamOperator<CartAddUuBean> javaBeanDs = keyedStream.map(new RichMapFunction<JSONObject, CartAddUuBean>() {
            private ValueState<String> lastCartDt;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastCartDt = getRuntimeContext().getState(new ValueStateDescriptor<String>("last_cart_dt", String.class));
            }

            @Override
            public CartAddUuBean map(JSONObject value) throws Exception {
                String curtDt = DateFormatUtil.toYmd(value.getString("create_time"));
                String lastDt = lastCartDt.value();
                Long uv = 0L;
                if (lastDt == null || lastDt.equals(curtDt)) {
                    uv = 1L;
                    lastCartDt.update(curtDt);
                }
                return new CartAddUuBean("",
                        "",
                        uv,
                        null);
            }
        });
        //todo 5 开窗聚合
        SingleOutputStreamOperator<CartAddUuBean> resultDS = javaBeanDs.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<CartAddUuBean>() {
                    @Override
                    public CartAddUuBean reduce(CartAddUuBean value1, CartAddUuBean value2) throws Exception {
                        value1.setCartAddUuCt(value1.getCartAddUuCt() + value2.getCartAddUuCt());
                        return value1;
                    }
                }, new AllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<CartAddUuBean> values, Collector<CartAddUuBean> out) throws Exception {
                        CartAddUuBean next = values.iterator().next();
                        out.collect(MyWindowFunction.getJavabeanFields(next, window));
                    }
                });
        //todo 6 将数据写出到clickHouse
        resultDS.print("result>>>>>>>>>>>>>>");
        resultDS.addSink(ClickHouseUtil.getSinkFunction("insert into dws_trade_cart_add_uu_window values(?,?,?,?)"));
        //todo 7 启动程序
        env.execute();
    }
}
